<template>
  <div class="pull-refresh-demo">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- 列表项 -->
        <div v-for="(item, index) in list" :key="index" class="list-item">
          <div class="item-content">
            <van-image
              :src="item.image"
              width="80"
              height="80"
              radius="4"
            />
            <div class="item-info">
              <div class="item-title">{{ item.title }}</div>
              <div class="item-desc">{{ item.desc }}</div>
              <div class="item-price">¥{{ item.price }}</div>
            </div>
          </div>
          <van-divider />
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 列表数据
const list = ref([])
// 下拉刷新相关
const refreshing = ref(false)
// 上拉加载相关
const loading = ref(false)
const finished = ref(false)

// 模拟数据生成
const generateItems = (startIndex, count) => {
  const items = []
  for (let i = startIndex; i < startIndex + count; i++) {
    items.push({
      title: `商品标题 ${i + 1}`,
      desc: `这是一个商品描述，用来测试多行文本的显示效果。商品编号：${i + 1}`,
      price: Math.floor(Math.random() * 1000),
      image: `https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg`
    })
  }
  return items
}

// 下拉刷新
const onRefresh = () => {
  // 重置列表数据
  finished.value = false
  list.value = []
  
  // 模拟异步请求
  setTimeout(() => {
    list.value = generateItems(0, 10)
    refreshing.value = false
  }, 1000)
}

// 上拉加载
const onLoad = () => {
  // 模拟异步请求
  setTimeout(() => {
    const lastIndex = list.value.length
    const newItems = generateItems(lastIndex, 10)
    list.value.push(...newItems)
    
    // 加载状态结束
    loading.value = false
    
    // 数据全部加载完成
    if (list.value.length >= 40) {
      finished.value = true
    }
  }, 1000)
}

// 初始化加载数据
onLoad()
</script>

<style scoped>
.pull-refresh-demo {
  min-height: 100vh;
  background: #f7f8fa;
}

.list-item {
  background: #fff;
  padding: 12px 16px;
}

.item-content {
  display: flex;
  gap: 12px;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin-bottom: 4px;
}

.item-desc {
  font-size: 14px;
  color: #969799;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.item-price {
  font-size: 16px;
  color: #ee0a24;
  font-weight: bold;
}

.van-divider {
  margin: 0;
}
</style>
